<template>
  <div class="health-reminder">
    <el-popover
      width="350"
      trigger="click"
      :visible="popoverVisible"
      @hide="popoverVisible = false"
    >
      <template #reference>
        <el-badge :value="unfinishedTasksCount" :hidden="unfinishedTasksCount === 0">
          <el-button type="primary" circle @click="togglePopover">
            <el-icon><Bell /></el-icon>
          </el-button>
        </el-badge>
      </template>
      
      <div class="reminder-content">
        <div class="reminder-header">
          <h3>健康打卡提醒</h3>
          <el-switch
            v-model="enableReminder"
            active-text="开启提醒"
            @change="handleReminderToggle"
          />
        </div>
        
        <div class="reminder-body">
          <template v-if="enableReminder">
            <div v-if="todayChecked" class="reminder-info success">
              <el-icon><CircleCheckFilled /></el-icon>
              <span>今日已完成健康打卡！</span>
            </div>
            <div v-else class="reminder-info warning">
              <el-icon><Timer /></el-icon>
              <span>今日尚未完成健康打卡</span>
            </div>
            
            <div class="stats-wrapper">
              <div class="stat-item">
                <div class="stat-value">{{ continuousDays }}</div>
                <div class="stat-label">连续打卡</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ totalTasksCompleted }}</div>
                <div class="stat-label">已完成</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ unfinishedTasksCount }}</div>
                <div class="stat-label">待完成</div>
              </div>
            </div>
            
            <div class="task-list">
              <div v-for="(task, index) in tasks" :key="index" class="task-item">
                <el-checkbox v-model="task.completed" :disabled="task.locked" @change="handleTaskChange(task)">
                  {{ task.name }}
                </el-checkbox>
                <div class="task-time" :class="{ 'text-danger': task.overdue }">
                  {{ task.timeText }}
                </div>
              </div>
            </div>
            
            <div class="reminder-actions">
              <el-button 
                type="primary" 
                :disabled="todayChecked"
                @click="goToHealthCheck"
              >
                {{ todayChecked ? '今日已打卡' : '立即打卡' }}
              </el-button>
            </div>
          </template>
          <div v-else class="reminder-disabled">
            <el-empty 
              description="打卡提醒已关闭" 
              :image-size="100"
            >
              <el-button @click="enableReminder = true">开启提醒</el-button>
            </el-empty>
          </div>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { Bell, CircleCheckFilled, Timer } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'

const router = useRouter()

// 控制弹出层显示
const popoverVisible = ref(false)

// 是否启用提醒
const enableReminder = ref(localStorage.getItem('enableHealthReminder') !== 'false')

// 打卡状态数据
const todayChecked = ref(false)
const continuousDays = ref(0)
const totalTasksCompleted = ref(0)
const unfinishedTasksCount = ref(0)

// 任务列表
const tasks = ref([
  {
    name: '今日健康打卡',
    completed: false,
    deadline: setTodayHours(22, 0), // 今天22:00
    locked: false,
    overdue: false
  },
  {
    name: '填写睡眠记录',
    completed: false,
    deadline: setTodayHours(10, 0), // 今天10:00
    locked: false,
    overdue: false
  },
  {
    name: '记录运动数据',
    completed: false,
    deadline: setTodayHours(20, 0), // 今天20:00
    locked: false,
    overdue: false
  }
])

// 设置今天的某一时刻
function setTodayHours(hours, minutes) {
  const date = new Date()
  date.setHours(hours, minutes, 0, 0)
  return date
}

// 计算任务的时间显示文本
const updateTaskTimeText = () => {
  const now = new Date()
  tasks.value.forEach(task => {
    const diff = task.deadline - now
    
    if (diff < 0) {
      task.timeText = '已过期'
      task.overdue = true
    } else if (diff < 60 * 60 * 1000) { // 小于1小时
      const minutes = Math.floor(diff / (60 * 1000))
      task.timeText = `剩余${minutes}分钟`
      task.overdue = false
    } else if (diff < 24 * 60 * 60 * 1000) { // 小于24小时
      const hours = Math.floor(diff / (60 * 60 * 1000))
      task.timeText = `剩余${hours}小时`
      task.overdue = false
    } else {
      task.timeText = `${task.deadline.getHours()}:${String(task.deadline.getMinutes()).padStart(2, '0')}`
      task.overdue = false
    }
  })
}

// 定时更新时间文本
let timeUpdateInterval = null

// 切换提醒显示状态
const togglePopover = () => {
  popoverVisible.value = !popoverVisible.value
  
  if (popoverVisible.value) {
    // 打开提醒时更新任务状态
    updateTaskTimeText()
  }
}

// 处理提醒开关切换
const handleReminderToggle = (val) => {
  localStorage.setItem('enableHealthReminder', val)
  
  if (val) {
    ElMessage.success('健康打卡提醒已开启')
    checkTodayStatus()
  } else {
    ElMessage.info('健康打卡提醒已关闭')
  }
}

// 处理任务状态变化
const handleTaskChange = (task) => {
  // 如果是第一个任务（今日健康打卡）被完成
  if (task.name === '今日健康打卡' && task.completed) {
    todayChecked.value = true
    ElMessage.success('恭喜完成今日健康打卡！')
    saveTaskStatus()
    
    // 模拟后端更新数据
    setTimeout(() => {
      continuousDays.value++
      totalTasksCompleted.value++
      updateUnfinishedCount()
    }, 500)
  }
  
  // 保存状态
  saveTaskStatus()
  updateUnfinishedCount()
}

// 更新未完成任务数量
const updateUnfinishedCount = () => {
  unfinishedTasksCount.value = tasks.value.filter(task => !task.completed).length
}

// 保存任务状态到localStorage
const saveTaskStatus = () => {
  const status = {
    todayChecked: todayChecked.value,
    tasks: tasks.value.map(task => ({
      name: task.name,
      completed: task.completed
    })),
    date: new Date().toDateString(),
    continuousDays: continuousDays.value,
    totalTasksCompleted: totalTasksCompleted.value
  }
  localStorage.setItem('healthCheckStatus', JSON.stringify(status))
}

// 从localStorage加载任务状态
const loadTaskStatus = () => {
  const status = localStorage.getItem('healthCheckStatus')
  if (status) {
    try {
      const parsed = JSON.parse(status)
      // 如果是今天的数据，则加载
      if (parsed.date === new Date().toDateString()) {
        todayChecked.value = parsed.todayChecked
        continuousDays.value = parsed.continuousDays || 0
        totalTasksCompleted.value = parsed.totalTasksCompleted || 0
        
        // 更新任务状态
        parsed.tasks.forEach((savedTask, index) => {
          if (index < tasks.value.length) {
            tasks.value[index].completed = savedTask.completed
          }
        })
      } else {
        // 如果不是今天的数据，需要重置
        resetDailyTasks()
        // 但保留累计数据
        continuousDays.value = parsed.continuousDays || 0
        totalTasksCompleted.value = parsed.totalTasksCompleted || 0
        
        // 如果不是昨天的数据，重置连续天数
        const yesterday = new Date()
        yesterday.setDate(yesterday.getDate() - 1)
        if (parsed.date !== yesterday.toDateString() && parsed.todayChecked) {
          continuousDays.value = 0
        }
      }
    } catch (e) {
      console.error('解析健康打卡状态数据失败:', e)
      resetDailyTasks()
    }
  } else {
    // 如果没有状态数据，初始化
    resetDailyTasks()
    continuousDays.value = 0
    totalTasksCompleted.value = 0
  }
  
  updateUnfinishedCount()
}

// 重置每日任务状态
const resetDailyTasks = () => {
  todayChecked.value = false
  tasks.value.forEach(task => {
    task.completed = false
    task.overdue = false
  })
}

// 跳转到健康打卡页面
const goToHealthCheck = () => {
  router.push('/health-check')
  popoverVisible.value = false
}

// 检查今日打卡状态（实际应该从API获取）
const checkTodayStatus = () => {
  // 这里模拟从后端获取当天打卡状态
  // 实际项目中应该调用API
  loadTaskStatus()
}

// 显示打卡提醒通知
const showReminder = () => {
  if (enableReminder.value && !todayChecked.value) {
    ElNotification({
      title: '健康打卡提醒',
      message: '今天还没有完成健康打卡，别忘了记录您的健康数据哦',
      type: 'warning',
      duration: 5000
    })
  }
}

onMounted(() => {
  // 加载状态
  checkTodayStatus()
  
  // 设置定时更新
  timeUpdateInterval = setInterval(() => {
    updateTaskTimeText()
  }, 60000) // 每分钟更新一次
  
  // 初始更新一次
  updateTaskTimeText()
  
  // 设置提醒检查
  setTimeout(() => {
    if (enableReminder.value && !todayChecked.value) {
      showReminder()
    }
  }, 5000) // 页面加载5秒后检查
})

onBeforeUnmount(() => {
  // 清除定时器
  if (timeUpdateInterval) {
    clearInterval(timeUpdateInterval)
  }
})
</script>

<style lang="scss" scoped>
.health-reminder {
  display: inline-block;
}

.reminder-content {
  .reminder-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h3 {
      margin: 0;
      color: #303133;
    }
  }
  
  .reminder-body {
    .reminder-info {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      padding: 10px;
      border-radius: 4px;
      
      .el-icon {
        margin-right: 8px;
        font-size: 18px;
      }
      
      &.success {
        background-color: #f0f9eb;
        color: #67c23a;
      }
      
      &.warning {
        background-color: #fdf6ec;
        color: #e6a23c;
      }
    }
    
    .stats-wrapper {
      display: flex;
      justify-content: space-around;
      margin-bottom: 15px;
      
      .stat-item {
        text-align: center;
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
        }
        
        .stat-label {
          font-size: 12px;
          color: #606266;
        }
      }
    }
    
    .task-list {
      margin-bottom: 15px;
      
      .task-item {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .task-time {
          font-size: 12px;
          color: #909399;
          
          &.text-danger {
            color: #f56c6c;
          }
        }
      }
    }
    
    .reminder-actions {
      text-align: center;
    }
    
    .reminder-disabled {
      padding: 20px 0;
    }
  }
}
</style> 